//
//  PicturePickerController.swift
//  SelectPhotos
//
//  Created by 李锡鹏 on 2017/6/19.
//  Copyright © 2017年 李锡鹏. All rights reserved.
//

import UIKit
import SnapKit
private var selectIndex:Int = 0
private var maxPictureCount:Int = 9
class PicturePickerController:UICollectionViewController {
    init() {
       super.init(collectionViewLayout: PicturePickerFlowLayout())
//        let long = UILongPressGestureRecognizer(target: self, action: #selector(handlelongGesture(longPress:)))
//        collectionView?.addGestureRecognizer(long)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor.white
        collectionView?.register(PicturePickerCell.self, forCellWithReuseIdentifier: "picturePickerID")
    }
    func handlelongGesture(longPress:UILongPressGestureRecognizer) {
        print("ceshi")
        // 在重写了collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        //这个函数后 长按事件会被该事件接受，不会触发 自定义的 除非 将collectionView 作为子视图
        switch longPress.state {
        case UIGestureRecognizerState.began:
            let indexPath = collectionView?.indexPathForItem(at: longPress.location(in: collectionView))
            if indexPath == nil {
                break
            }
            if (indexPath?.item)! >= pictures.count {
                return
            }
            collectionView?.beginInteractiveMovementForItem(at: indexPath!)
            break
        case UIGestureRecognizerState.changed:
            let indexPath = collectionView?.indexPathForItem(at: longPress.location(in: collectionView))
            if (indexPath?.item)! >= pictures.count {
                break
            }
            collectionView?.updateInteractiveMovementTargetPosition(longPress.location(in: collectionView))
            break
        case UIGestureRecognizerState.ended:
            collectionView?.endInteractiveMovement()
            break
        default:
            collectionView?.cancelInteractiveMovement()
            break
        }
    }
    lazy var pictures = [UIImage]()
    
}

extension PicturePickerController {
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count + (pictures.count == maxPictureCount ? 0 :1)
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "picturePickerID", for: indexPath) as! PicturePickerCell
        cell.picturePickerDelegate = self
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        if  indexPath.item >= pictures.count
        {
            return false
        }
        return true
    }
    override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        if destinationIndexPath.item >= pictures.count {
            
            collectionView.moveItem(at: destinationIndexPath, to: sourceIndexPath)
        }
    }
}
extension PicturePickerController : PicturePickerCellDelegate {
    @objc func PicturePickerCellAdd(cell: PicturePickerCell) {
        // 判断是否允许访问相册
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
            print("无权限")
        }
        selectIndex = (collectionView?.indexPath(for: cell)?.item)!
        let picker = UIImagePickerController()
        picker.delegate = self
        present(picker, animated: true, completion: nil)
    }
    @objc func PicturePickerCellDelete(cell: PicturePickerCell) {
        let indexPath = collectionView?.indexPath(for: cell)
        if (indexPath?.item)! >= pictures.count {
            return
        }
        pictures.remove(at: (indexPath?.item)!)
        collectionView?.deleteItems(at: [indexPath!])
    }
}
extension PicturePickerController :UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.reSize(w: 200, h:200)
        if selectIndex >= pictures.count {
            pictures.append(scaleImage)
        }
        else
        {
            pictures[selectIndex] = scaleImage
        }
        self.collectionView?.reloadData()
        dismiss(animated: true, completion: nil)
    }
}
class PicturePickerFlowLayout:UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        let count :CGFloat = 3
        let margin :CGFloat = UIScreen.main.scale * 4
        let w = ((collectionView?.bounds.width)! - (count+1)*margin)/count
        itemSize = CGSize(width: w, height: w)
        sectionInset = UIEdgeInsets(top: 2*margin, left: margin, bottom: 0, right: margin)
        minimumLineSpacing = margin
        minimumInteritemSpacing = margin
        
    }
}
